package com.rick.awarenessdemo

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.CameraPosition
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.services.core.PoiItem
import com.rick.awarenessdemo.base.BaseActivity
import com.rick.awarenessdemo.databinding.ActivityMapBinding

/**
 * 确认目的地
 */
class MapActivity :
    BaseActivity<ActivityMapBinding>(R.layout.activity_map, true) {
    companion object {
        private const val KEY_POI_ITEM = "KEY_POI_ITEM"

        @JvmStatic
        fun startForResult(activity: Activity, poiItem: PoiItem, reqCode: Int) {
            val intent = Intent(activity, MapActivity::class.java)
            intent.putExtra(KEY_POI_ITEM, poiItem)
            activity.startActivityForResult(intent, reqCode)
        }

        /**
         * 从 ActivityResult 的 Intent 获取数据
         */
        @JvmStatic
        fun getIntentResult(intent: Intent?) = intent?.getParcelableExtra<PoiItem>(KEY_POI_ITEM)
    }

    override fun init(savedInstanceState: Bundle?, binding: ActivityMapBinding) {
        binding.map.onCreate(savedInstanceState)
        val poiItem = intent.getParcelableExtra<PoiItem>(KEY_POI_ITEM)!!
        binding.btn.setOnClickListener {
            val intent = Intent()
            intent.putExtra(KEY_POI_ITEM, poiItem)
            setResult(RESULT_OK, intent)
            finish()
        }
        val latLng = LatLng(poiItem.latLonPoint.latitude, poiItem.latLonPoint.longitude) // 经纬度
        // 标记点
        binding.map.map.addMarker(
            MarkerOptions().position(latLng).title(poiItem.title).snippet(poiItem.snippet)
        )
        // 视窗移动到点
        binding.map.map.moveCamera(
            CameraUpdateFactory.newCameraPosition(
                CameraPosition(
                    latLng,
                    18f,
                    0f,
                    0f
                )
            )
        )
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.map.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        binding.map.onResume()
    }

    override fun onPause() {
        super.onPause()
        binding.map.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        binding.map.onSaveInstanceState(outState)
    }
}